﻿using UnityEngine;
using System.Collections;

public class Giro : MonoBehaviour 
{
    public float speed = 10;
    public float angleOffset = 0;
    public float maxAngel = 45;


    public bool verticalReverse = false;
    public bool horizontalReverse = false;

    private float angel;
    public virtual void Start() 
    {
        angel = CalcGiroAngel();
	}
	
	public virtual void FixedUpdate () 
    {
        UpdateAngel();
	}

    private void UpdateAngel()
    {
        float diferent = CalcGiroAngel() - angel;

        if (Mathf.Abs(diferent) > 180)
        {
            angel += diferent > 0 ? 360 : -360;
            diferent = 0;
        }

        angel += diferent * Time.fixedDeltaTime * speed;
    }

    private float CalcGiroAngel()
    {
        Vector2 acceleration = GetAcceleration();
        return CheckAngelLimits(Mathf.Atan2(acceleration.x, acceleration.y) * 180 / Mathf.PI) 
            * (horizontalReverse ? -1 : 1) 
            + (verticalReverse ? 180 : 0);
    }

    public Vector2 GetAcceleration()
    {
        return new Vector2(-Input.acceleration.x, Input.acceleration.y);
    }

    private float CheckAngelLimits(float angel)
    {
        if (angel <= 0 && maxAngel - 180 < angel)
            return maxAngel - 180 + angleOffset;
        if (angel > 0 && 180 - maxAngel > angel)
            return 180 - maxAngel + angleOffset;
        return angel + angleOffset;
    }

    public float GetAngel()
    {
        return angel;
    }

    public Vector2 GetDirection()
    {
        return new Vector2(Mathf.Sin(angel * Mathf.Deg2Rad), Mathf.Cos(angel * Mathf.Deg2Rad)).normalized;
    }
}
